package com.tnsw.noxnox;

import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.tnsw.coreutils.AsyncManager;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.telephony.TelephonyManager;
import android.util.Log;

public class Registra extends AsyncTask<String, Integer, Long>{
	
	private String tag = "Registra";
	private Context context;
	private String email;
	private int currentState = -1;
	
	private AsyncManager asyncManager;
	
	public Registra(Context context) {
		this.context = context;
		this.asyncManager = AsyncManager.getInstance();
	}
	
	private Long getEmailFromGoogle() {
		this.currentState = 0;
		Log.d(tag, "Getting email from Google");
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet("https://www.googleapis.com/oauth2/v1/userinfo");
		
		try {
			SharedPreferences settings = this.context.getSharedPreferences("SignupActivity", 0);
		    String token = settings.getString("token", "");
		    Log.d(tag, "using token={" + token + "} from cache");
		    
			//List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			//nameValuePairs.add(new BasicNameValuePair("Authorization", "auth " + token));
			
			httpGet.addHeader("Authorization", "OAuth " + token);
			
			//httpGet.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
	        // Execute HTTP Post Request
	        HttpResponse response = httpClient.execute(httpGet);
	        
	        String ret = EntityUtils.toString(response.getEntity());
	        Log.d(tag, ret);
	        this.asyncManager.appendNetworkLog(ret);
	        
	        JSONObject jsObj = new JSONObject(ret);
	        this.email = jsObj.getString("email");
	        Log.d(tag, "Email=" + email);
		} catch (Exception e) {
			Log.e(tag, e.toString(), e);
			return(1l);
		}
		
		return(0l);
	}
	
	private Long register2TNSW() {
		this.currentState = 1;
		Log.d(tag, "Registering to TNSW");
		SharedPreferences settings = this.context.getSharedPreferences("SignupActivity", 0);
	    String registrationId = settings.getString("registration_id", "");
	    
		TelephonyManager tm = (TelephonyManager) this.context.getSystemService(Context.TELEPHONY_SERVICE);
		String imei = tm.getDeviceId();
		
		ArrayList<NameValuePair> a = new ArrayList<NameValuePair>();
		a.add(new BasicNameValuePair("cmd", "register"));
		a.add(new BasicNameValuePair("device_id", registrationId));
		a.add(new BasicNameValuePair("project_number", "518191396700"));
		a.add(new BasicNameValuePair("email", this.email));
		a.add(new BasicNameValuePair("imei", imei));
		
		HttpResponse response = AsyncManager.doHttpPost("http://172.16.50.192/PredictWeb/GCM.ashx", a);
		Log.d(tag, "HTTP StatusCode=" + String.valueOf(response.getStatusLine().getStatusCode()));
		
		return(0l);
	}
	
	protected void onPostExecute(Long result) {
		super.onPostExecute(result);

	}
	
	@Override
	protected Long doInBackground(String... params) {
		Log.d(tag, "executing.. doInBackground(" + params[0] + ")");
		
		if (params[0].equals("0")) {
			this.getEmailFromGoogle();
			this.register2TNSW();
		}
		
		return 0l;
	}

}
